﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using ArxivatDeDocuments.Formularis;
using ArxivatDeDocuments.ObjectesDeDades;

namespace ArxivatDeDocuments.ObjectesDeNegoci
{
    class RecorrerDirectorisController : Controller
    {
        private frmRecorrerDirectoris frm;
        private System.Threading.Thread th;
        
        private List<Document> _documentsTrobats;
        public List<Document> documentsTrobats
        {
            get
            {
                return _documentsTrobats;
            }
        }

        private enum EnumNivellCarpeta
        { 
            PPTI,
            Exercici,
            Impost,
            Periode
        }

        public override void run()
        {
            _documentsTrobats = new List<Document>();

            frm = new frmRecorrerDirectoris();
            frm.ValorMaximBarraProgres = ComptaDirectoris(Properties.Settings.Default.pathToPPTIFolder);

            th = new System.Threading.Thread(Processa);
            th.Start();

            frm.ShowDialog();

            if (!frm.CancelPressed)
                this.ProximaAccio = enumProximaAccio.ProximPas;
            else
                this.ProximaAccio = enumProximaAccio.TancarPrograma;            
        }

        private int ComptaDirectoris(String path)
        {
            int resultat = 1;
            foreach (string d in Directory.GetDirectories(path))
            {
                resultat = resultat + ComptaDirectoris(d);
            }
            return resultat;
        }

        private void Processa()
        {
            Processa(Properties.Settings.Default.pathToPPTIFolder, new Document(), EnumNivellCarpeta.PPTI);
            frm.Estat = frmRecorrerDirectoris.EstatRecorregut.Acabat;            
        }

        private void Processa(String path, Document documentBase, EnumNivellCarpeta nivell )
        {            
            //Indiquem que estem fent al formulari
            if (nivell != EnumNivellCarpeta.PPTI)
                frm.setInfoAccioActual("Examinant el directori " + path.Substring(Properties.Settings.Default.pathToPPTIFolder.Length));
            
            //Omplim les dades del document de base
            switch (nivell)
            {
                case EnumNivellCarpeta.PPTI:
                    //No cal fer res
                    break;

                case EnumNivellCarpeta.Exercici:
                    DirectoryInfo dir1 = new DirectoryInfo(path);
                    int any;
                    Exercici exercici = null;
                    
                    if (int.TryParse(dir1.Name, out any))
                        exercici = (from Exercici e in Contexte.getExercicis() where e.Any == any select e).FirstOrDefault();

                    if (exercici != null)
                        documentBase.exercici = exercici;
                    else
                        //Exercici desconegut
                        return;
                    break;

                case EnumNivellCarpeta.Impost:
                    DirectoryInfo dir2 = new DirectoryInfo(path);
                    Impost impost = null;

                    impost = (from Impost i in Contexte.getImpostos() where i.Codi == dir2.Name select i).FirstOrDefault();

                    if (impost != null)
                        documentBase.impost = impost;
                    else
                        //impost desconegut
                        return;
                    break;

                case EnumNivellCarpeta.Periode:
                    DirectoryInfo dir3 = new DirectoryInfo(path);
                    Periode periode = null;

                    periode = (from Periode p in Contexte.getPeriodes() where p.Codi == dir3.Name select p).FirstOrDefault();

                    if (periode != null)
                        documentBase.periode = periode;
                    else
                        //periode desconegut
                        return;
                    break;

                default:
                    //Directori desconegut
                    return;
            }

            //System.Threading.Thread.Sleep(1000);
            if (nivell == EnumNivellCarpeta.Periode)
            {
                foreach (string f in Directory.GetFiles(path))
                {
                    TractaDocument(path, f, documentBase);
                }
            }
            else
            {
                foreach (string d in Directory.GetDirectories(path))
                {
                    if (!frm.CancelPressed)
                    {
                        Processa(d, documentBase, nivell+1);
                    }
                    else
                        frm.Estat = frmRecorrerDirectoris.EstatRecorregut.Cancelat;
                }
            }

            frm.AvancaBarraProgres();
        }

        private void TractaDocument(String path, String fitxer, Document documentBase)
        {
            //TODO: Verificar que l'extensió és la correcta segons l'impost
            FileInfo f = new FileInfo(fitxer);

            switch (documentBase.impost.Codi.ToUpper())
            {
                case "115":
                case "123":
                case "130":
                case "131":
                case "310":
                case "311":
                case "INTRASTAT":
                    //Amb html
                    if (f.Extension.ToUpper() != ".HTM" && f.Extension.ToUpper() != ".HTML") return;
                    break;

                case "100":
                case "111":
                case "180":
                case "184":
                case "190":
                case "200":
                case "202":
                case "303":
                case "309":
                case "340":
                case "347":
                case "349":
                case "390":
                case "950":
                case "193":
                case "569":
                case "216":
                case "296":
                default:
                    if (f.Extension.ToUpper()!=".PDF") return;
                    break;
            }

            if (f.Name.Length >= 11 && (Client.Verificar_NIF(f.Name.Substring(2,9)) || Client.Verificar_CIF(f.Name.Substring(2,9))))
            {
                Client client = (from c in Contexte.getClients() where c.Nif == f.Name.Substring(2, 9) select c).FirstOrDefault();
                if (client == null)
                {
                    client = new Client();
                    client.Nif = f.Name.Substring(2, 9);
                    Contexte.addClient(client);
                }

                Document document = new Document();
                document.exercici = documentBase.exercici;
                document.impost = documentBase.impost;
                document.periode = documentBase.periode;
                document.Fitxer = f;
                document.client = client;

                _documentsTrobats.Add(document);
            }

        }
    }

     
}
